package cs4280.ass2.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cs4280.ass2.entity.Member;
import cs4280.ass2.entity.User;
import cs4280.ass2.persistence.UserDao;

public class LoginAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String login = req.getParameter("login");
		String password = req.getParameter("password");

		User user = UserDao.getInstance().retrieveUserByLoginPwd(login, password);
		if (user != null) {
			HttpSession session = req.getSession();
			session.setAttribute("loggedInUser", user);
			if (user instanceof Member) {
				resp.sendRedirect(req.getContextPath()+"/index.jsp");
			} else {
				// admin user.
				resp.sendRedirect(req.getContextPath()+"/admin/index.jsp");
			}
		}else{
			// login fail.
			req.setAttribute("message.error", "message.error.login.fail");
			getServletContext().getRequestDispatcher("/login.jsp").forward(req, resp);
		}
	}
}
